﻿using System.Text;
using TrackSystem.IO.Data;
using TrackSystem.IO.Models;

namespace TrackSystem.IO.Protocol
{
    /// <summary>
    /// 高度计通信协议
    /// </summary>
    public class AltimeterProtocol : ProtocolBase
    {
        private int startTicks;
        private bool bSendR;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="name"></param>
        public AltimeterProtocol(string name)
            : base()
        {
            NeedInit = false;
            Name = name;
            Tx_r = new byte[1] { 0x5A };
            bSendR = false;
        }

        /// <summary>
        /// 生成读取寄存器的通讯帧
        /// </summary>
        /// <returns></returns>
        public override byte[] GenerateReadFrame(out int NeedRecvLen)
        {
            startTicks = Environment.TickCount;
            // 上次的发送没有收到正确回复，bSend没有被置位
            if (bSendR)
            {
                Fail_R++;
                // 失败超过3次，成功次数清零
                if (Fail_R >= 3)
                {
                    Succ_R = 0;
                }
            }
            bSendR = true;

            NeedRecvLen = 4;
            return Tx_r;
        }


        /// <summary>
        /// 根据收到的内容进行处理
        /// </summary>
        /// <param name="buffer"></param>
        /// <returns></returns>
        public override bool ProcessReadFrame(byte[] buffer)
        {
            Rx_r = buffer;
            Lapse = Environment.TickCount - startTicks;

            try
            {
                string frame = Encoding.UTF8.GetString(buffer);
                string[] ar_line = frame.Split('m');
                RegFactory.Instance.SetVal(RegNameList[0], double.Parse(ar_line[0]));
            }
            catch (Exception)
            {
                return false;
            }

            Succ_R++;
            bSendR = false;     // 正确收到，标志位变为false
            Fail_R = 0;         // 通信成功，则将失败次数清零
            return true;
        }


        /// <summary>
        /// 生成写入寄存器的通讯帧
        /// </summary>
        /// <param name="NeedRecvLen"></param>
        /// <returns></returns>
        public override byte[] GenerateWriteFrame(out int NeedRecvLen)
        {
            startTicks = Environment.TickCount;
            NeedRecvLen = 0;
            return null;
        }

        /// <summary>
        /// 根据收到的内容进行处理
        /// </summary>
        /// <param name="buffer"></param>
        /// <returns></returns>
        public override bool ProcessWriteFrame(byte[] buffer)
        {
            Lapse = Environment.TickCount - startTicks;
            return true;
        }
    }
}
